package com.topscomm.work.controller;

import java.util.*;

import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.http.HttpUtil;
import com.topscomm.base.service.IBasePermissionManageService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.meet.service.IMeetManageService;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.work.pojo.WorkScheduleEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.UnauthorizedException;
import com.topscomm.cbo.pojo.CboSystemErrorLogEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.constant.TapHttpErrorCode;
import com.topscomm.tap.constant.TapHttpStatus;
import com.topscomm.tap.util.ErrorLogUtil;
import com.topscomm.work.service.IWorkScheduleService;

/**
 * @description:对外的接口
 * @author: zhanglongfei
 * @date: 2020年11月27日下午5:36:42
 * @modify:
 */
@RestController
@RequestMapping("api/schedule")
public class ScheduleInterfaceController {
	@Autowired
	private IWorkScheduleService workScheduleService;
	@Autowired
	private IBasePermissionManageService basePermissionManageService;
	/**
	 * @description:批量保存日程接口
	 * @param paraMap
	 * 数据格式：
	 * {
	 * "datas":[{
	 * 'name': '',
	 * 'begintime':'',
	 * 'handleusercode':'',
	 * 'handleusername':'',
	 * ...日程属性,
	 * selectUsers:{
	 * 'usercodes': '',
	 * 'usernames': '',
	 * 'deptcodes': '',
	 * 'deptnames': ''
	 * },
	 * remindList:[{},{}]
	 * }]
	 * }
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月27日下午6:01:12
	 * @modify:
	 */
	@SuppressWarnings("unchecked")
	@PostMapping(value = "mulitSubmitWorkSchedule")
	public ResponseResult<Object> mulitSubmitWorkSchedule(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			List<Map<String, Object>> datas = null;
			if (paraMap.containsKey("datas"))
				datas = (List<Map<String, Object>>) paraMap.get("datas");
			else {
				return ResponseResult.error("无有效数据 datas");
			}
			String isSendMessage = ConvertUtil.convertToString(paraMap.get("isSendMessage"));
			// 使用false判断isSendMessage，是因为默认是发送消息，除非对方传递isSendMessage为false
			workScheduleService.mulitSubmitWorkSchedule(datas, "true".equals(isSendMessage));
			return ResponseResult.ok("保存成功");
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}
	/**
	  *
	  * @author xinfushuo
	  * @param  scheduleList : {[userCode,beginTime,endTime]}
	  * @throws
	  * @return
	  * @date 2022/12/19
	  * @modify
	  */
	@PostMapping(value = "checkConflict")
	public ResponseResult<Object>checkConflict(@RequestBody List<CaseInsensitiveMap<String,Object>> scheduleList){
		List<Map<String,Object>> resultList = new ArrayList<>();
		if(scheduleList.isEmpty()){
			return ResponseResult.ok(resultList);
		}
		for (Map<String,Object> schedule : scheduleList) {
			String usercode = ConvertUtil.convertToString(schedule.get("userCode"));
			String begintime = SQLAdapter.toDateLong(DateUtil.dateToString(
			DateUtil.stringToDate(ConvertUtil.convertToString(schedule.get("beginTime"))), "yyyy-MM-dd HH:mm:ss"));
			String endtime = SQLAdapter.toDateLong(DateUtil.dateToString(
			DateUtil.stringToDate(ConvertUtil.convertToString(schedule.get("endTime"))), "yyyy-MM-dd HH:mm:ss"));
			//查询该人在此时的日程
			Set<String> shares = new HashSet<>();
			shares.add(usercode);
			//拼接日期条件
			StringBufferProxy scheduleSql = new StringBufferProxy();
			scheduleSql.appendSingle("( endtime > {0} and begintime < {1})", begintime, endtime);
			List<String> filedList = new ArrayList<String>();
			filedList.add(WorkScheduleEntity.FieldId);
			filedList.add(WorkScheduleEntity.FieldEndtime);
			filedList.add(WorkScheduleEntity.FieldBegintime);
			filedList.add(WorkScheduleEntity.FieldName);
			// 查询这段时间内所有日程
			List<Map<String, Object>> workScheduleMapList = this.workScheduleService
			.queryMapFieldsByWhere(scheduleSql.toString(), filedList);
			//无日程 无冲突
			if(workScheduleMapList.isEmpty()){
				continue;
			}
			List<Map<String,Object>> result = basePermissionManageService.checkConflict(shares,workScheduleMapList);
			resultList.addAll(result);
		}
		return  ResponseResult.ok(resultList);
	}

	/**
	 * @description:撤销日程接口
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年11月27日下午5:36:23
	 * @modify:
	 */
	@PostMapping(value = "cancelWorkSchedule")
	public ResponseResult<Object> cancelWorkSchedule(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			String sourceapp = ConvertUtil.convertToString(paraMap.get("sourceapp"));
			String sourcetype = ConvertUtil.convertToString(paraMap.get("sourcetype"));
			String sourceids = ConvertUtil.convertToString(paraMap.get("sourceids"));
			workScheduleService.cancelWorkSchedule(sourceapp, sourcetype, sourceids);
			return ResponseResult.error("取消成功");
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	protected ResponseResult<Object> handleControllerException(Exception ex) {
		if (ex instanceof MessageException) {
			return handleControllerMessage(ex.getMessage());
		}
		CboSystemErrorLogEntity logEntity = ErrorLogUtil.writeLog(ex);
		// UnauthorizedException异常处理
		if (ex instanceof UnauthorizedException) {
			return ResponseResult.error(((UnauthorizedException) ex).getStatus(), TapHttpErrorCode.UNAUTHORIZED_CLIENT, ex.getMessage());
		}
		if (logEntity != null && !StringUtil.isEmpty(logEntity.getDisplayerror())) {
			return ResponseResult.error(TapHttpStatus.HTTP_INTERNAL_ERROR, TapHttpErrorCode.ERROR_FORMAT, logEntity.getDisplayerror());
		}
		// 通用Exception异常处理
		return ResponseResult.error(TapHttpStatus.HTTP_INTERNAL_ERROR, TapHttpErrorCode.ERROR, ex.getMessage());
	}

	protected ResponseResult<Object> handleControllerMessage(String message) {
		// 通用Exception异常处理
		return ResponseResult.error(TapHttpStatus.HTTP_INTERNAL_ERROR, TapHttpErrorCode.ERROR_MESSAGE, message);
	}
}
